/**
 * 鉴权
 */
const jwt = require("jsonwebtoken")

module.exports = async (req, res, next) => {
    if($config._cer.includes(req.path) && req.method !== 'OPTIONS') {
        next();
    }else{
        try {
            let _access = jwt.verify(req.headers['x-access-token'], $config._sk),
                _client = await $client._get(req.headers['x-access-token']);

            if(_client) {
                console.log(`Welcome ${_access.name} to visit`);
                if($config._aer.includes(req.path) && _client.role_id !== 0) {
                    res.status(400).send({
                        code: 400,
                        msg: '请联系管理员添加'
                    })
                }else{
                    next();
                }
            } else {
                res.status(401).send({
                    code: 401,
                    msg: 'Token expired.'
                })
            }
        } catch (e) {
            res.status(403).send({
                code: 403,
                msg: 'Invalid token.'
            })
        }
    }
}
